import { getAvatarApi } from '@/api/file'
import { loginApi, getInfoApi, loginOutApi } from '@/api/user'
import { ActionContext } from 'vuex'
import store from '..'
import { sendHeartbeat } from "@/utils/heartbeat"
export interface userState {
  token: string,
  info: object,
  user_id: string,
  is_super: boolean,
  is_teacher: boolean,
  userIcon: string,
  CourseId: string,
  isMobile: boolean,
  tabName: string,
  courseCount: number,
}
const state = (): userState => ({
  token: '', // 登录token
  info: {},  // 用户信息
  user_id: '',
  is_super: false,
  is_teacher: false,
  userIcon: '',
  CourseId: '',
  isMobile: false,
  tabName: 'task',
  courseCount: 0,
})


// getters
const getters = {
  token(state: userState) {
    return state.token
  }
}

// mutations
const mutations = {
  tokenChange(state: userState, token: string) {
    state.token = token
  },
  infoChange(state: userState, info: object) {
    state.info = info
  },
  roleChange(state: userState, role: { user_id: string, is_super: boolean, is_teacher: boolean }) {
    state.user_id = role.user_id;
    state.is_super = role.is_super;
    state.is_teacher = role.is_teacher;
  },
  getUserAvatarUrl(state: userState, url: string) {
    state.userIcon = url;
  },
  setCourseId(state: userState, courseId: string) {
    state.CourseId = courseId;
  },
  setDeviceType(state: userState, isMobile: boolean) {
    state.isMobile = isMobile;
  },
  setTabName(state: userState, tabName: string) {
    state.tabName = tabName;
  },
  clearState(state: userState) {
    state.token = ''
    state.info = {}
    state.user_id = ''
    // state.userIcon = ''
    state.CourseId = ''
  },
  updateCourseCount(state: userState, count: number) {
    state.courseCount = count;
  },

}

// actions
const actions = {
  login({ commit, dispatch }: ActionContext<userState, userState>, params: any) {
    return new Promise((resolve, reject) => {
      loginApi(params)
        .then(res => {
          commit('tokenChange', res.data.token)
          commit('roleChange', {
            user_id: res.data.user_id,
            is_super: res.data.is_super,
            is_teacher: res.data.is_teacher
          })
          // 检查登录设备类型
          if (/iPhone|iPad|iPod|Android/i.test(window.navigator.userAgent)) {
            commit('setDeviceType', true);
          }

          dispatch('getInfo', { token: res.data.token })
            .then(infoRes => {
              resolve(res.data.token)
            })
          getAvatarApi({ user_id: store.state.user.user_id }).then((response) => {
            commit('getUserAvatarUrl', response.data)
            // console.log("登录时候获取头像：response.data = "+response.data )
          })
        }).catch(err => {
          reject(err)
        })

    })
  },
  // get user info after user logined
  getInfo({ commit }: ActionContext<userState, userState>, params: any) {
    return new Promise((resolve, reject) => {
      getInfoApi(params)
        .then(res => {
          commit('infoChange', res.data.info)
          resolve(res.data.info)
        })
    })
  },

  // login out the system after user click the loginOut button
  loginOut({ commit }: ActionContext<userState, userState>) {
    loginOutApi()
      .then(res => {
        commit('clearState')
      })
      .catch(error => {

      })
      .finally(() => {
        localStorage.removeItem('tabs')
        localStorage.removeItem('vuex')
        sessionStorage.removeItem('vuex')
        location.reload()
      })
  }
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}
